#include "FileDriver.h"
#include "stdio.h"

FileDriver::FileDriver()
:m_is_open(false)
{
}

bool FileDriver::file_open(string filename)
{
	if(true == m_is_open) {
		file_close();
	}

	m_fstream.open(/*filename.c_str()*/"send_file",
			ios::in/* | fstream::out |
			fstream::app | fstream::binary*/);
	if(true == m_fstream.fail()) {
		cout<<"FileDriver::file_open: "
				"Fail to open file: "
				<<filename<<endl;
		return false;
	}

	m_is_open = true;
	return true;
}

void FileDriver::file_close() {
	m_fstream.clear();
	m_fstream.close();
	m_is_open = false;
}

int FileDriver::file_write(void* buffer) {
	if(true == m_is_open && NULL != buffer) {
		m_fstream << buffer <<flush;
		if(true == m_fstream.good()) {
			return 0;
		}
		else {
			cout<<"FileDriver::file_write: "
					"Error occurred when write"
					" buffer content to file"
					<<endl;
			return -1;
		}
	}
	else if(false == m_is_open) {
		cout<<"FileDriver::file_write: "
				"Error occurred, FileDriver has not "
				"opened any file."<<endl;
		return -2;
	}
	else {
		cout<<"FileDriver::file_write: "
				"Buffer to be wrote is empty"<<endl;
		return -3;
	}
}

int FileDriver::file_read(void* buffer, size_t read_size) {
	if(true == m_is_open && NULL != buffer) {
		m_fstream.read((char*)buffer, read_size);
		return 0;
	/*	if(true != m_fstream.fail()) {
			return 0;
		}
		else {
			cout<<"FileDriver::file_read: "
					"Error occurred when read"
					" content into buffer "
					"from file"<<endl;
			return -1;
		}*/
	}
	else if(false == m_is_open) {
		cout<<"FileDriver::file_read: "
				"Error occurred, FileDriver has not "
				"opened any file."<<endl;
		return -2;
	}
	else {
		cout<<"FileDriver::file_read: "
				"The buffer to be read is empty"<<endl;
		return -3;
	}
}
